'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import styles from './register.module.css';

interface RegisterFormData {
  name: string;
  email: string;
  pwd: string;
  confirmPassword: string;
}

const Register = () => {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState<RegisterFormData>({
    name: '',
    email: '',
    pwd: '',
    confirmPassword: ''
  });
  const [message, setMessage] = useState({ type: '', content: '' });

  // 显示消息
  const showMessage = (type: 'success' | 'error' | 'info', content: string) => {
    setMessage({ type, content });
    setTimeout(() => setMessage({ type: '', content: '' }), 3000);
  };

  // 表单验证
  const validateForm = () => {
    if (!formData.name.trim()) {
      showMessage('error', '请输入用户名');
      return false;
    }
    if (formData.name.length < 4 || formData.name.length > 16) {
      showMessage('error', '用户名长度应为4-16个字符');
      return false;
    }
    if (!/^[a-zA-Z0-9]+$/.test(formData.name)) {
      showMessage('error', '用户名只能包含字母和数字');
      return false;
    }
    if (!formData.email.trim()) {
      showMessage('error', '请输入邮箱');
      return false;
    }
    if (!/^\S+@\S+\.\S+$/.test(formData.email)) {
      showMessage('error', '请输入有效的邮箱地址');
      return false;
    }
    if (!formData.pwd.trim()) {
      showMessage('error', '请输入密码');
      return false;
    }
    if (formData.pwd.length < 6 || formData.pwd.length > 20) {
      showMessage('error', '密码长度应为6-20个字符');
      return false;
    }
    if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{6,20}$/.test(formData.pwd)) {
      showMessage('error', '密码需包含大小写字母和数字');
      return false;
    }
    if (formData.pwd !== formData.confirmPassword) {
      showMessage('error', '两次输入的密码不匹配');
      return false;
    }
    return true;
  };

  // 处理输入变化
  const handleInputChange = (field: keyof RegisterFormData, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // 处理注册
  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) return;

    try {
      setLoading(true);
      const { confirmPassword, ...registerData } = formData;
      
      const response = await fetch('http://127.0.0.1:8000/api/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(registerData)
      });

      const data = await response.json();

      if (data.code === 200) {
        showMessage('success', data.message || '注册成功');
        // 重置表单
        setFormData({
          name: '',
          email: '',
          pwd: '',
          confirmPassword: ''
        });
        // 延迟跳转到登录页面
        setTimeout(() => {
          router.push('/login');
        }, 1500);
      } else {
        showMessage('error', data.message || '注册失败');
      }
    } catch (error) {
      console.error('注册请求失败详情:', error);
      showMessage('error', '注册失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.container}>
      {/* 背景层 */}
      <div className={styles.backgroundLayer}>
        <div className={styles.backgroundImage}></div>
        <div className={styles.backgroundOverlay}></div>
      </div>

      {/* 内容区 */}
      <div className={styles.content}>
        {/* 头部 - 与主页面风格一致 */}
        <div className={styles.loginHeader}>
          <Image 
            src="/logo.png" 
            alt="Logo" 
            width={100} 
            height={100}
            className={styles.logo}
          />
          <h1 className={styles.welcomeText}>Ganmo</h1>
          <p className={styles.subtitle}>释放压力 <span className={styles.dot}>·</span> 享受生活</p>
        </div>

        {/* 表单卡片 */}
        <div className={styles.loginCard}>
          <div className={styles.cardHeader}>
            <h2 className={styles.cardTitle}>用户注册</h2>
          </div>
          
          <form onSubmit={handleRegister}>
            {/* 用户名输入 */}
            <div className={styles.inputGroup}>
              <div className={styles.inputWrapper}>
                <span className={styles.inputIcon}>👤</span>
                <input
                  type="text"
                  placeholder="用户名 (4-16位字母或数字)"
                  className={styles.loginInput}
                  value={formData.name}
                  onChange={(e) => handleInputChange('name', e.target.value)}
                  required
                />
              </div>
            </div>

            {/* 邮箱输入 */}
            <div className={styles.inputGroup}>
              <div className={styles.inputWrapper}>
                <span className={styles.inputIcon}>✉️</span>
                <input
                  type="email"
                  placeholder="邮箱"
                  className={styles.loginInput}
                  value={formData.email}
                  onChange={(e) => handleInputChange('email', e.target.value)}
                  required
                />
              </div>
            </div>

            {/* 密码输入 */}
            <div className={styles.inputGroup}>
              <div className={styles.inputWrapper}>
                <span className={styles.inputIcon}>🔒</span>
                <input
                  type="password"
                  placeholder="密码 (6-20位，需含大小写和数字)"
                  className={styles.loginInput}
                  value={formData.pwd}
                  onChange={(e) => handleInputChange('pwd', e.target.value)}
                  required
                />
              </div>
            </div>

            {/* 确认密码输入 */}
            <div className={styles.inputGroup}>
              <div className={styles.inputWrapper}>
                <span className={styles.inputIcon}>🔒</span>
                <input
                  type="password"
                  placeholder="确认密码"
                  className={styles.loginInput}
                  value={formData.confirmPassword}
                  onChange={(e) => handleInputChange('confirmPassword', e.target.value)}
                  required
                />
              </div>
            </div>

            {/* 提交按钮 */}
            <button
              type="submit"
              className={styles.loginBtn}
              disabled={loading}
            >
              {loading ? '注册中...' : '立即注册'}
            </button>
          </form>

          {/* 底部链接 */}
          <div className={styles.bottomLinks}>
            <span 
              className={styles.linkText}
              onClick={() => router.push('/login')}
            >
              已有账号？去登录
            </span>
          </div>
        </div>
      </div>

      {/* 消息提示 */}
      {message.content && (
        <div className={`${styles.message} ${styles[message.type]}`}>
          {message.content}
        </div>
      )}
    </div>
  );
};

export default Register;